<template>
  <div id="roles">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }"
        ><span>首页</span></el-breadcrumb-item
      >
      <el-breadcrumb-item><span>权限管理</span></el-breadcrumb-item>
      <el-breadcrumb-item><span>角色列表</span></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="roles-container">
      <el-button type="primary" class="addBtn" @click="addVisible = true"
        >添加角色</el-button
      >
      <el-dialog
        title="添加角色"
        :visible.sync="addVisible"
        width="50%"
        @close="addDown"
      >
        <el-form
          :model="addRoles"
          ref="rolesRef"
          :rules="rolesRules"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoles.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoles.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="addEditor">确 定</el-button>
        </span>
      </el-dialog>
      <el-table
        :data="getRoles"
        style="width: 100%; font-size: 12px; margin-top: 15px"
        stripe
        border
      >
        <el-table-column type="expand">
          <!-- 展开后第一层 -->
          <template #default="scope">
            <el-row
              :class="['bdBottom', 'center', i1 === 0 ? 'bdTop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="6" class="center">
                <el-tag closable @close="remove3(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级权限 -->
              <el-col :span="18">
                <!-- 渲染二级 -->
                <el-row
                  :class="[i1 === 0 ? '' : 'bdTop', 'bdRight', 'center']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6" class="center">
                    <el-tag
                      closable
                      type="success"
                      @close="remove3(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      type="warning"
                      @close="remove3(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editorId(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="delId(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="permissions(scope.row)"
              >分配权限</el-button
            >
            <!-- 编辑角色 -->
            <el-dialog
              title="编辑角色"
              :visible.sync="editorVisible"
              width="50%"
              @close="editorDown"
            >
              <el-form
                :model="editorRoles"
                ref="editorRef"
                :rules="rolesRules"
                label-width="80px"
              >
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="editorRoles.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                  <el-input v-model="editorRoles.roleDesc"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="editorVisible = false">取 消</el-button>
                <el-button type="primary" @click="goEditor">确 定</el-button>
              </span>
            </el-dialog>
            <!-- 分配权限 -->
            <el-dialog title="分配权限" :visible.sync="setVisible" width="50%" @close="setRightDialog">
              <el-tree
                :data="getStation"
                :props="defaultProps"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys="defKeys"
                ref="allTree"
              ></el-tree>
              <span slot="footer" class="dialog-footer">
                <el-button @click="setVisible = false">取 消</el-button>
                <el-button type="primary" @click="allToRight"
                  >确 定</el-button
                >
              </span>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data() {
    return {
      // 所有角色信息
      getRoles: [],
      // 添加角色
      addRoles: {
        roleName: '',
        roleDesc: '',
      },
      addVisible: false,
      // 表单验证
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      // 编辑角色
      editorRoles: {},
      editorVisible: false,
      // 分配权限
      getStation: [],
      setVisible: false,
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认勾选的节点ID值
      defKeys:[],
      // 当前即将分配权限的id
      roleId:'',  
    }
  },
  created() {
    this.getRoList()
  },
  methods: {
    async getRoList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getRoles = res.data
      // console.log(this.getRoles)
    },
    // 关闭添加弹出框
    addDown() {
      this.$refs.rolesRef.resetFields()
    },
    // 添加表单整体验证
    addEditor() {
      this.$refs.rolesRef.validate(async (vail) => {
        if (vail == false) return this.$message.error('表单验证失败')
        const { data: res } = await this.$http.post('roles', this.addRoles)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRoList()
        this.addVisible = false
      })
    },
    // 编辑角色
    async editorId(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editorRoles = res.data
      this.editorVisible = true
      console.log(this.editorRoles)
    },
    // 关闭编辑弹出框
    editorDown() {
      this.$refs.editorRef.resetFields()
    },
    // 编辑表单整体验证
    goEditor() {
      this.$refs.editorRef.validate(async (vail) => {
        if (vail == false) return this.$message.error('表单验证失败')
        const { data: res } = await this.$http.put(
          `roles/${this.editorRoles.roleId}`,
          this.editorRoles
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRoList()
        this.editorVisible = false
      })
    },
    // 删除角色
    delId(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`)
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.$message.success('删除成功')
          this.getRoList()
        })
        .catch(() => {
          this.$message.error('已取消删除')
        })
    },
    // 关闭第三级角色权限
    remove3(roleId, rightID) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${roleId.id}/rights/${rightID}`
          )
          if (res.meta.status !== 200)
            return this.$message.error('删除权限失败')
          this.$message.success('删除成功')
          roleId.children = res.data
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 分配权限
    async permissions(rows) {
      this.roleId = rows.id;
      const { data: res } = await this.$http.get(`rights/tree`)
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.getStation = res.data
      this.getLeafKey(rows,this.defKeys)
      this.setVisible = true
      console.log(this.getStation)
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到defkeys数组中
    getLeafKey(node,arr){
      // 如果当前node节点不包含children属性，则是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
     
      node.children.forEach(item =>{
        // console.log(item);
        this.getLeafKey(item,arr)
      })
      
    },
    // 关闭分配权限窗口
    setRightDialog(){
      this.defKeys = [];
    },
    async allToRight(){
      const keys = [
        ...this.$refs.allTree.getCheckedKeys(),
        ...this.$refs.allTree.getHalfCheckedNodes()
      ]
      const idStr = keys.join(',')
      console.log(idStr);
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:idStr
      })
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getRoList()
      this.setVisible = false
    }
  },
}
</script>

<style lang="less" scoped>
.roles-container {
  padding: 20px;
  background-color: #fff;
  margin-top: 15px;
}
.roles-container .addBtn {
  padding: 12px 20px;
  font-size: 14px;
}
.el-button {
  font-size: 12px;
  padding: 7px 15px;
}
.el-tag {
  margin: 7px;
}
.bdBottom {
  border-bottom: 1px solid #ccc;
}
.bdTop {
  border-top: 1px solid #ccc;
}
.bdRight {
  border-left: 1px solid #ccc;
}
.center {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>